package com.example.zjsr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.zjsr.common.Key;
import com.example.zjsr.common.ServerResponse;
import com.example.zjsr.dao.UserDao;
import com.example.zjsr.domain.*;
import com.example.zjsr.service.UserService;
import com.example.zjsr.util.AliyunMailUtil;
import com.example.zjsr.util.MD5;
import com.example.zjsr.util.PostUtil;
import com.example.zjsr.util.SmsRandomCodeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserDao userDao;

    @Override
    public ServerResponse<Object> importUsers(List<Object> users) {
        try{
            /**
             * 这里仅仅临时导入数据,没有进行邮箱号的判断等，不完善。
             */
            for(Object obj:users){
                User user = (User) obj;
                user.setPassword(MD5.md52(user.getPassword()));
                userDao.insertBackUser(user);
            }
            return ServerResponse.createBySuccess("导入成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("导入失败");
        }
    }

    @Override
    public ServerResponse<Object> importUsers2(List<Object> score) {
        try{
            /**
             * 这里仅仅临时导入数据,没有进行邮箱号的判断等，不完善。
             */
            for(Object obj:score){
                Score score1 = (Score) obj;
                userDao.insertBackUser2(score1);
            }
            return ServerResponse.createBySuccess("导入成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("导入失败");
        }
    }

    /**
     * 注册业务逻辑类
     * @param userVo
     * @return
     */
    @Override
    public ServerResponse<String> register(UserVo userVo) {
        //保证验证码不能为空
        if(userVo.getCheckCode()==null || "".equals(userVo.getCheckCode())){
            return ServerResponse.createByErrorMsg("验证码不能为空");
        }
        //前端传递的验证码和redis中的checkCode进行比对
        if(!userVo.getCheckCode().equals(redisTemplate.boundValueOps("email_"+userVo.getEmail()).get())){
            return ServerResponse.createByErrorMsg("验证码错误");
        }
        if(userVo.getLoginName()==null || userVo.getLoginName().equals("")){
            return ServerResponse.createByErrorMsg("登录用户名不能为空");
        }
        if(userVo.getEmail()==null||userVo.getEmail().equals("")){
            return ServerResponse.createByErrorMsg("邮箱不能为空");
        }
        //用户名、邮箱需要唯一
        int resultCount = userDao.checkLoginName(userVo.getLoginName());
        if(resultCount > 0){
            return ServerResponse.createByErrorMsg("登录用户名已存在");
        }
        resultCount = userDao.checkEmail(userVo.getEmail());
        if(resultCount > 0){
            return ServerResponse.createByErrorMsg("邮箱已存在");
        }
        //userVo <- User
        User user = new User();
        user.setSchool(userVo.getSchool());
        user.setEmail(userVo.getEmail());
        user.setPassword(MD5.md52(userVo.getPassword()));
        user.setCity(userVo.getCity());
        user.setProvince(userVo.getProvince());
        user.setLoginName(userVo.getLoginName());
        user.setUsername(userVo.getUsername());
        user.setRoleId(userVo.getRoleId());
        user.setClasses(userVo.getClasses());
        resultCount = userDao.insert(user);
        if(resultCount < 0){
            return ServerResponse.createByACCOUNTError("用户注册失败");
        }
        return ServerResponse.createBySuccessMsg("注册成功");
    }

    /**
     * 邮箱注册验证码生成逻辑类
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> generateCheckCode(String email) {
        synchronized (this){
            //邮箱非空验证
            if(email==null||"".equals(email)){
                return ServerResponse.createByACCOUNTError("邮箱不能为空,请填入有效地址");
            }
            //生成随机的6位数字验证码
            String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
            //调用邮箱发送
            boolean status=AliyunMailUtil.sendMail(email,"浙江树人大学虚拟仿真实验项目用户注册","您的验证码为："+verificationCode+"。此验证码三分钟内有效，请及时注册。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！感谢您的注册，祝您使用愉快！");
//            SmsPojo smsPojo = new SmsPojo();
//            smsPojo.setToAddress(email);
//            smsPojo.setSubject("用户注册");
//            smsPojo.setContent("注册码为："+verificationCode);
//            if(SmsUtil.sendTextMail(smsPojo)){
                //发送成功保存邮箱地址对应的验证码 todo 已解决
                // redis中保存邮箱验证码三分钟 todo 解决安全 一个email对应唯一的验证码
//            Map<String,String> map = new HashMap<>();
//            map.put(email,verificationCode);
//                  redisTemplate.opsForHash().putAll("email",map);
            if(status){
                redisTemplate.boundValueOps("email_"+email).set(verificationCode,180,TimeUnit.SECONDS);
                // todo 发送的验证码拼接了之前的验证码？？ 获取content内容时候出现getContent现象
                // todo 2019年8月28日09:23:18 接口中屏蔽验证码
                return ServerResponse.createBySuccess();
            } else{
                return ServerResponse.createByACCOUNTError("邮件发送失败");
            }
        }
    }

    /**
     * 忘记密码时候，根据邮箱返回验证码
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //验证邮箱是否存在
        int resultCount = userDao.checkEmail(email);
        if(resultCount != 1){
            return ServerResponse.createByErrorMsg("邮箱不存在！");
        }
        //邮箱非空验证
        if(email==null||"".equals(email)){
            return ServerResponse.createByErrorMsg("邮箱不能为空,请填入有效地址");
        }
        //生成随机的验证码
        String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
        //调用邮箱发送
        try{
            boolean status= AliyunMailUtil.sendMail(email,"浙江树人大学虚拟仿真实验项目密码重置","您的验证码为："+verificationCode+"。此验证码三分钟内有效，请及时重置密码。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！");
            if(status){
                //发送成功保存邮箱地址对应的验证码 todo 3分钟 已解决
                redisTemplate.boundValueOps("forget_"+email).set(verificationCode,180,TimeUnit.SECONDS);
                return ServerResponse.createBySuccess();
            }else{
                return ServerResponse.createByErrorMsg("邮件发送失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("邮件发送失败");
        }

//        SmsPojo smsPojo = new SmsPojo();
//        smsPojo.setToAddress(email);
//        smsPojo.setSubject("忘记密码");
//        smsPojo.setContent("验证码为："+verificationCode);
    }

    @Override
    public List<User> findAll(User user) {
        List<User> userList = userDao.selectAll(user);
        return userList;
    }

    @Override
    public ServerResponse<String> insertBackUser(UserVo userVo) {
        // vo <- pojo
        User user = new User();
        user.setRoleId(userVo.getRoleId());
        user.setLoginName(userVo.getLoginName());
        user.setPassword(MD5.md52(userVo.getPassword()));
        user.setUsername(userVo.getUsername());
        user.setSchool(userVo.getSchool());
        user.setProvince(userVo.getProvince());
        user.setCity(userVo.getCity());
        user.setEmail(userVo.getEmail());
        user.setClasses(userVo.getClasses());
        int resultCount = userDao.insertBackUser(user);
        if(resultCount != 1){
            return ServerResponse.createByACCOUNTError("新增后台用户失败");
        }
        return ServerResponse.createBySuccessMsg("新增后台用户成功");
    }

    @Override
    public ServerResponse<String> deleteByUserId(Integer id) {
        if(id==null){
            return ServerResponse.createByErrorMsg("参数错误");
        }
        int effectNum = userDao.deleteByUserId(id);
        if(effectNum != 1){
            return ServerResponse.createByErrorMsg("删除失败");
        }
        return ServerResponse.createBySuccess("删除成功");
    }

    @Override
    public ServerResponse<String> updateBackendUser(User user) {

        int resultCount = userDao.updateBackendUser(user);
        if(resultCount != 1){
            return ServerResponse.createByErrorMsg("修改后台用户失败");
        }
        return ServerResponse.createBySuccessMsg("修改后台用户成功");
    }

    @Override
    public List<User> findByParams(User user) {

        List<User> userList = userDao.selectByParams(user);
        return userList;
    }

    @Override
    public ServerResponse<Integer> accountUser() {
        int count = userDao.selectUserCounts();
        return ServerResponse.createBySuccess(count);
    }

    @Override
    public ServerResponse<User> findById(Integer id) {
        User user = userDao.findById(id);
        if(user == null){
            return ServerResponse.createByErrorMsg("查询用户失败");
        }
        return ServerResponse.createBySuccess(user);
    }

    @Override
    public int insertIlabUser(UserVo userVo) {
        User user = new User();
        user.setUsername(userVo.getUsername());
        user.setLoginName(userVo.getLoginName());
        user.setSchool(userVo.getSchool());
        user.setProvince(userVo.getProvince());
        user.setCity(userVo.getCity());
        user.setRoleId(userVo.getRoleId());
        user.setPassword(userVo.getPassword());
        user.setEmail(userVo.getEmail());
        return userDao.inserIlabUser(user);
    }

    @Override
    public User selectUserByUserId(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public User selectUserByLoginName(String loginName) {
        return userDao.findByLoginName(loginName);
    }

    @Transactional
    @Override
    public ServerResponse<String> updatePassword(UserVo userVo) {
        String checkCode = (String) redisTemplate.boundValueOps("forget_"+userVo.getEmail()).get();
        if(!userVo.getCheckCode().equals(checkCode)){
            return ServerResponse.createByErrorMsg("验证码错误");
        }
        if(!userVo.getNewPassword().equals(userVo.getConfirmPassword())){
            return ServerResponse.createByErrorMsg("密码不一致，请重新输入");
        }
        User user = new User();
        user.setEmail(userVo.getEmail());
        user.setPassword(MD5.md52(userVo.getNewPassword()));
        int effectNum = userDao.updatePasswordByEmail(user);
        //通过邮箱获取到用户的用户名、角色
        User u = userDao.checkLogin(user.getEmail());
        Operate operate=new Operate();
        operate.setOperateStyle("用户修改密码");
        operate.setOperateUser(u.getUsername());
        if(u.getRoleId()==1){
            operate.setOperateRoot("管理员");
        }else if(u.getRoleId()==2){
            operate.setOperateRoot("教师");
        }else if(u.getRoleId()==3){
            operate.setOperateRoot("评审账户");
        }else if(u.getRoleId()==4){
            operate.setOperateRoot("学生");
        }
        operate.setOperateStatus("成功");
        userDao.insertOperate(operate);
        if(effectNum == 1 ){
            //将时间赋值
            userDao.upDatePasswordTime(u.getLoginName());
            return ServerResponse.createBySuccessMsg("更新密码成功");
        }
        return ServerResponse.createByErrorMsg("更新密码失败");
    }


    @Override
    public ServerResponse getFruitField() {
        List<FruitMapping> fruitMappingList=userDao.getFruitField();
        return ServerResponse.createBySuccess(fruitMappingList);
    }


    @Override
    public void expertLogin(User expertLoginUser) {
        userDao.expertLogin(expertLoginUser);
    }


    @Override
    public void deleteUser() {
        userDao.deleteUser();
    }


    @Override
    public ServerResponse addPlatform(Platform platform) {
        int checkStatus=userDao.addPlatform(platform);
        if(checkStatus!=0){
            return ServerResponse.createBySuccessMsg("成功上传直播平台信息");
        }else{
            return ServerResponse.createByACCOUNTError("上传直播平台信息失败");
        }
    }


    @Override
    public ServerResponse deletePlatform(Integer platformId) {
        int checkDelStatus=userDao.deletePlatform(platformId);
        if(checkDelStatus!=0){
            return ServerResponse.createBySuccessMsg("成功删除该直播平台信息");
        }else{
            return ServerResponse.createByACCOUNTError("删除该直播平台信息失败");
        }
    }

    @Override
    public ServerResponse updatePlatform(Platform platform) {
        int checkUpdateStatus=userDao.updatePlatform(platform);
        if(checkUpdateStatus!=0){
            return ServerResponse.createBySuccessMsg("修改直播平台信息成功");
        }else{
            return ServerResponse.createByACCOUNTError("修改失败");
        }
    }


    @Override
    public ServerResponse getPlatform(Integer platformId) {
        List<Platform> platformList=userDao.getPlatform(platformId);
        return ServerResponse.createBySuccess(platformList);
    }


    @Transactional
    @Override
    public ServerResponse addBroadcast(Broadcast broadcast,Integer uId) {
        Broadcast broadcast1=userDao.getBroadcastByUser(uId);//根据用户编号来获取到旧的直播参数
        if(null!=broadcast1){
            userDao.deleteProjectDesign(broadcast1.getBroadcastId());//删除直播参数
            userDao.deleteBroadcast(broadcast1.getBroadcastId());//删除直播参数
        }
        userDao.addBroadcast(broadcast);//添加新的直播参数
        List<ProjectDesign> projectDesignList=broadcast.getProjectDesignList();
        projectDesignList.forEach(projectDesign -> {
            projectDesign.setBroadcastId(broadcast.getBroadcastId());
        });
        int checkStatus=userDao.addProjectDesign(projectDesignList);//添加新的直播参数
        if(checkStatus!=0){
            return ServerResponse.createBySuccessMsg("成功添加直播方案！");
        }else{
            return ServerResponse.createByAuthMsg("添加直播方案设计失败！");
        }
    }


    @Override
    public ServerResponse getBroadcast(Integer id) {
        List<Broadcast> broadcastList=userDao.getBroadcast(id);
        return ServerResponse.createBySuccess(broadcastList);
    }

    @Override
    public ServerResponse addHeadline(String headlineTitle) {
        Headline headline=new Headline();
        headline.setHeadlineTitle(headlineTitle);
        int checkAddStatus=userDao.addHeadline(headline);
        if(checkAddStatus!=0){
            return ServerResponse.createBySuccess("成功添加题目一级标题",headline.getHeadlineId());

        }else{
            return ServerResponse.createByAuthMsg("添加题目一级标题失败");
        }
    }


    @Override
    public ServerResponse getHeadline() {
        List<Headline> headlineList=userDao.getHeadline();
        return ServerResponse.createBySuccess(headlineList);
    }

    @Override
    public ServerResponse updateHeadline(Headline headline) {
        int checkUpdateStatus=userDao.updateHeadline(headline);
        if(checkUpdateStatus!=0){
            return ServerResponse.createBySuccessMsg("成功修改题目大标题");
        }else{
            return ServerResponse.createByACCOUNTError("修改题目大标题失败");
        }
    }


    @Transactional
    @Override
    public ServerResponse addTopic(Topic topic) {
        int checkAddStatus=userDao.addTopic(topic);//添加题目主题
        for (int i = 0; i < topic.getAnswerList().size(); i++) {
            topic.getAnswerList().get(i).setTopicId(topic.getTopicId());
        }
        userDao.addAnswer(topic.getAnswerList());//添加题目信息回答详细信息
        if(checkAddStatus!=0){
            return ServerResponse.createBySuccessMsg("成功添加题目描述");
        }else{
            return ServerResponse.createByACCOUNTError("添加题目描述失败");
        }
    }

    @Override
    public ServerResponse updateTopic(Topic topic,Integer choose) {
        List<Answer> answerList=topic.getAnswerList();
        if(null!=answerList){
            for (int i = 0; i < answerList.size(); i++) {
                Answer answer=answerList.get(i);
                userDao.updateAnswer(answer);
            }
        }
        try {
            userDao.updateTopic(topic);
            Answer answerStatus=userDao.getAnswerStatus(choose);
            userDao.updateAnswerStatus(answerStatus.getTopicId());
            userDao.updateAnswerCheckStatus(choose);
            return ServerResponse.createBySuccessMsg("成功修改题目描述");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByACCOUNTError("修改题目描述失败");
        }
    }

    @Override
    public ServerResponse getTopic(Integer headlineId) {
        List<Topic> topicList=userDao.getTopic(headlineId);
        return ServerResponse.createBySuccess(topicList);
    }

    @Transactional
    @Override
    public ServerResponse addAnswer(List<Answer> answerList) {
        int checkAddStatus=userDao.addAnswer(answerList);
        if(checkAddStatus!=0){
            return ServerResponse.createBySuccessMsg("成功添加答案图片");
        }else{
            return ServerResponse.createByACCOUNTError("添加答案图片失败");
        }
    }


    @Override
    public ServerResponse updateAnswer(Answer answer) {
        Answer answerStatus=userDao.getAnswerStatus(answer.getAnswerId());
        if(answer.isStatus()){
            userDao.updateAnswerStatus(answerStatus.getTopicId());
        }
        int checkUpdateStatus=userDao.updateAnswer(answer);
        if(checkUpdateStatus!=0){
            return ServerResponse.createBySuccessMsg("成功修改答案图片");
        }else{
            return ServerResponse.createByACCOUNTError("修改答案图片失败");
        }
    }

    @Override
    public ServerResponse getAnswer(Integer topicId) {
        List<Answer> answerList=userDao.getAnswer(topicId);
       return ServerResponse.createBySuccess(answerList);
    }

    @Override
    public ServerResponse getAllAnswer(Integer headlineId) {
        /**
         * 根据题目标题编号来获取到题目单个的标题信息
         */
      List<Headline> headlineList=userDao.getAllAnswer(headlineId);
        for (int k = 0; k < headlineList.size(); k++) {
            Headline headline=headlineList.get(k);
            List<Topic> topicList=headline.getTopicList();
            if(topicList.size()!=0){
                for (int i = 0; i < topicList.size(); i++) {
                    Integer topicId=topicList.get(i).getTopicId();
                    List<Answer> answerList=userDao.getAnswer(topicId);
                    for (int j = 0; j < answerList.size(); j++) {
                        if(answerList.get(j).isStatus()){
                            topicList.get(i).setStatusId(answerList.get(j).getAnswerId());
                            topicList.get(i).setIndexItem(j);
                        }
                    }
                    topicList.get(i).setAnswerList(answerList);
                }
            }
            else{
                headlineList.remove(k);
                k--;
            }
        }
        return ServerResponse.createBySuccess(headlineList);
    }

    @Override
    public ServerResponse deleteAnswers(Integer answerId) {
        int checkDeleteStatus=userDao.deleteAnswers(answerId);
        if(checkDeleteStatus!=0){
            return ServerResponse.createBySuccessMsg("成功删除答案图片");
        }else{
            return ServerResponse.createByACCOUNTError("删除答案图片失败");
        }
    }

    @Transactional
    @Override
    public ServerResponse deleteTopic(Integer topicId) {
        int checkDeleteTopic=userDao.deleteTopic(topicId);
        userDao.deleteAnswerByTopic(topicId);
        if(checkDeleteTopic!=0){
            return ServerResponse.createBySuccessMsg("成功删除题目");
        }else{
            return ServerResponse.createByACCOUNTError("删除题目失败");
        }
    }


    @Override
    public ServerResponse deleteHeadline(Integer headlineId) {
      List<Topic> topicList=userDao.getTopic(headlineId);
      topicList.forEach(topic -> {
          userDao.deleteAnswerByTopic(topic.getTopicId());
          userDao.deleteTopic(topic.getTopicId());
      });
       int checkDeleteHeadline=userDao.deleteHeadline(headlineId);
       if(checkDeleteHeadline!=0){
           return ServerResponse.createBySuccessMsg("成功删除大标题");
       }else{
           return ServerResponse.createByACCOUNTError("删除大标题失败");
       }
    }

    @Override
    public ServerResponse getOperateInfo(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Operate> operateList=userDao.getOperateInfo();
        PageInfo<Operate> operatePageInfo=new PageInfo<>(operateList);
        return ServerResponse.createBySuccess(operatePageInfo);
    }


    @Override
    public List<DownOperate> downLoadOperateInfo() {
        return userDao.downLoadOperateInfo();
    }

    @Override
    public ServerResponse<String> updateMD5Password() {
        List<User> userList=userDao.getUsers();
        for (int i = 0; i < userList.size(); i++) {
            User user=userList.get(i);
            user.setPassword(MD5.md52(user.getPassword()));
        }
        for (int i = 0; i <userList.size(); i++) {
            User user=userList.get(i);
            userDao.updateMD5Password(user);
        }
        return null;
    }

    @Override
    public ServerResponse getScore(Integer pageNum, Integer pageSize,User user) {
        PageHelper.startPage(pageNum,pageSize);
        List<Score> scoreList=userDao.getScore(user);
        PageInfo<Score> scorePageInfo=new PageInfo<>(scoreList);
        return ServerResponse.createBySuccess(scorePageInfo);
    }

    @Override
    public ServerResponse getScoreById(Integer scoreId) {
        Score score=userDao.getScoreById(scoreId);
        return ServerResponse.createBySuccess(score);
    }

    @Override
    public ServerResponse deleteScoreById(Integer scoreId) {
        int i=userDao.deleteScoreById(scoreId);
        if(i!=0){
            return ServerResponse.createBySuccess("成功删除");
        }else{
            return ServerResponse.createBySuccessMsg("删除失败");
        }
    }

    @Override
    public ServerResponse readScoreById(Integer scoreId, String teacherComment) {
        int i=userDao.readScoreById(scoreId,teacherComment);
        if(i!=0){
            return ServerResponse.createBySuccess("成功批改");
        }else{
            return ServerResponse.createBySuccessMsg("批改失败");
        }
    }

    @Override
    public ServerResponse addScore(Score scores, User user) {
        //实验结束时间
//        long startDate = new Date().getTime();
//        //实验开始时间
//        long  endDate=startDate+scores.getExperimentScore()*60*1000;

        long endDate = new Date().getTime();
        //实验开始时间
        long  startDate=endDate-scores.getExperimentScore()*60*1000;
        //实验用时
        int timeUsed =scores.getExperimentScore();
        if(null!=user.getAccessToken()){
            String originId= UUID.randomUUID().toString();
            // 注释 用户登录名
            String username = user.getLoginName();
            // 项目名称
            // String projectTitle = "接口连通公测项目"; todo important 这是ilab测试平台的项目名称
            String projectTitle = "基于大数据分析的电商直播运营设计与决策优化虚拟仿真实验";// 正式的申报项目
            // 实验状态
            int status = 1;//完成
            // 实验得分
            int score =scores.getTotalScore();
            String issuerId = String.valueOf(Key.issuerId);
            //用户信息
            UserJson userJson=new UserJson();
            userJson.setUsername(username);
            userJson.setTitle(projectTitle);
            userJson.setStatus(status);
            userJson.setScore(score);
            userJson.setStartTime(startDate);
            userJson.setEndTime(endDate);
            userJson.setTimeUsed(timeUsed*60);
            userJson.setAppid(Integer.valueOf(issuerId));
            userJson.setOriginId(originId);
            System.out.println("userJson="+userJson);
            //步骤信息
            Steps steps=new Steps();
            steps.setSeq(1);
            steps.setTitle("步骤一");
            steps.setStartTime(startDate+1000);
            steps.setEndTime(startDate+3000);
            steps.setTimeUsed(2);
            steps.setExpectTime(1);
            steps.setMaxScore(10);
            steps.setScore(10);
            steps.setRepeatCount(1);
            steps.setEvaluation("优");
            steps.setScoringModel("考察点");
            steps.setRemarks("备注");
            List<Steps> stepsList=new ArrayList<>();
            stepsList.add(steps);
            userJson.setSteps(stepsList);
            String json= JSONObject.toJSONString(userJson);
            System.out.println("json="+json);
//        param.put("username", username);
//        param.put("projectTitle", projectTitle);
//        param.put("status", status);
//        param.put("score", score);
//        param.put("startDate", startDate);
//        param.put("endDate", endDate);
//        param.put("timeUsed", timeUsed);
//        param.put("issuerId", issuerId);//todo 已解决 2019年9月23日20:20:42

            try {
                String code= PostUtil.post(user.getAccessToken(),json,"application/json");
                System.out.println("调用实验结果接口的返回码==================" + code);
                JSONObject jsonObject= JSON.parseObject(code);
                if(jsonObject.getInteger("code")!=0){
                    return ServerResponse.createByErrorMsg("数据插入失败！");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByErrorMsg("数据插入失败！");
            }
        }
        scores.setUserId(user.getId());
        scores.setExperimentScore(timeUsed);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(startDate);
        scores.setExperimentDate(cal.getTime());
        userDao.addScore(scores);
        Operate operate=new Operate();
        operate.setOperateStyle("ilab用户提交成绩");
        operate.setOperateUser(user.getUsername());
        if(user.getRoleId()==1){
            operate.setOperateRoot("管理员");
        }else if(user.getRoleId()==2){
            operate.setOperateRoot("教师");
        }else if(user.getRoleId()==3){
            operate.setOperateRoot("评审账户");
        }else if(user.getRoleId()==4){
            operate.setOperateRoot("学生");
        }
        operate.setOperateStatus("成功");
        operate.setOperateDetail(scores+"");
        userDao.insertOperate(operate);
        return ServerResponse.createBySuccess("成功提交成绩");
    }


    @Override
    public int ilabInsertUser(UserVo userVo) {
        User user = new User();
        user.setSchool(userVo.getSchool());
        user.setEmail(userVo.getEmail());
        user.setPassword(MD5.md52(userVo.getPassword()));
        user.setCity(userVo.getCity());
        user.setProvince(userVo.getProvince());
        user.setLoginName(userVo.getLoginName());
        user.setUsername(userVo.getUsername());
        user.setRoleId(userVo.getRoleId());
        userDao.insert(user);
        return user.getId();
    }

    @Override
    public ServerResponse<Integer> accountExp() {
        int times=userDao.accountExp();
        return ServerResponse.createBySuccess(times);
    }

    @Override
    public ServerResponse<Integer> countTotalExpTime() {
        int experimentTime=userDao.countTotalExpTime();
        return  ServerResponse.createBySuccess(experimentTime);
    }
}
